package pay.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;
import pay.commont.MessageBindingType;
import pay.commont.MessageType;
import pay.dao.*;
import pay.entity.*;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MessageUtils {

    public String templateReplace(String template, AuthenticatedGameEntity game, ContestItemEntity contestItem) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
        String formattedDate = dateFormat.format(game.getGameStart());
        return template
                .replace("{gameName}", game.getName())
                .replace("{contestItemName}", contestItem.getName())
                .replace("{date}", formattedDate)
                .replace("{address}", game.getAddress());
    }

    public String templateReplace(String template,
                                  OrdersEntity order,
                                  GoodMapper goodMapper,
                                  AddressMapper addressMapper,
                                  OrderGoodMapper orderGoodMapper) {
        String orderGoodsNameFormat = this.getPostOrderGoodsNameFormat(order, orderGoodMapper, goodMapper);
        var addressEntity = addressMapper.selectOne(new QueryWrapper<AddressEntity>().eq("id", order.getAddressId()));
        return template
                .replace("{formatGoodsName}", orderGoodsNameFormat)
                .replace("{name}", addressEntity.getName())
                .replace("{phone}", addressEntity.getPhone())
                .replace("{address}",
                        addressEntity.getProvince() +
                                addressEntity.getCity() +
                                addressEntity.getDistrict() +
                                addressEntity.getAddress())
                .replace("{shippingCompanyName}",
                        order.getShippingCompanyName() == null ? "" : order.getShippingCompanyName())
                .replace("{shippingNumber}",
                        order.getShippingNumber() == null ? "" : order.getShippingNumber());
    }

    public String templateReplace(String template, ContestItemUserEntity contestItemUserEntity) {
        return template.replace("{playerId}", contestItemUserEntity.getPlayerId());
    }

    public String templateReplace(String template,
                                  AuthenticatedGameDraftMapper authenticatedGameDraftMapper,
                                  AuthenticatedGameAuditLogMapper authenticatedGameAuditLogMapper,
                                  Integer gameAuditId) {
        AuthenticatedGameDao authenticatedGameDao = SpringContextUtils.getBean(AuthenticatedGameDao.class);

        var gameAuditLog = authenticatedGameAuditLogMapper.selectOne(new QueryWrapper<AuthenticatedGameAuditLogEntity>().eq("id", gameAuditId));
        AuthenticatedGameEntity game = authenticatedGameDao.selectOne(new QueryWrapper<AuthenticatedGameEntity>().eq("id", gameAuditLog.getAuthenticatedGameDraftId()));
        String replaced = template.replace("{gameName}", game.getName());
        if (gameAuditLog.getReason() != null) {
            return replaced.replace("{reason}", gameAuditLog.getReason());
        } else {
            return replaced;
        }
    }

    public MessageEntity getDetail(MessageEntity messageEntity) {
        if (messageEntity.getTemplateId() != null) {
            if (messageEntity.getBindingType().equals(MessageBindingType.ORDER.getCode())) {
                if (messageEntity.getType().equals(MessageType.POST.getCode())) {
                    // 邮寄订单格式化
                    AddressMapper addressMapper = SpringContextUtils.getBean(AddressMapper.class);
                    OrderGoodMapper orderGoodMapper = SpringContextUtils.getBean(OrderGoodMapper.class);
                    GoodMapper goodMapper = SpringContextUtils.getBean(GoodMapper.class);
                    OrderMapper orderMapper = SpringContextUtils.getBean(OrderMapper.class);
                    TemplateMapper templateMapper = SpringContextUtils.getBean(TemplateMapper.class);

                    var order = orderMapper.selectOne(new QueryWrapper<OrdersEntity>().eq("id", messageEntity.getBindingId()));
                    var template = templateMapper.selectById(messageEntity.getTemplateId());
                    if (template != null && order != null) {
                        messageEntity.setContent(
                                templateReplace(
                                        template.getContent(),
                                        order,
                                        goodMapper,
                                        addressMapper,
                                        orderGoodMapper
                                )
                        );
                    }
                } else {
                    AuthenticatedGameDao authenticatedGameDao = SpringContextUtils.getBean(AuthenticatedGameDao.class);
                    ContestItemMapper contestItemMapper = SpringContextUtils.getBean(ContestItemMapper.class);
                    ContestItemUserMapper contestItemUserMapper = SpringContextUtils.getBean(ContestItemUserMapper.class);
                    OrderMapper orderMapper = SpringContextUtils.getBean(OrderMapper.class);
                    TemplateMapper templateMapper = SpringContextUtils.getBean(TemplateMapper.class);
                    var order = orderMapper.selectOne(new QueryWrapper<OrdersEntity>().eq("id", messageEntity.getBindingId()));
                    ContestItemEntity contestItem = null;
                    if (order != null) {
                        var itemUser = contestItemUserMapper.selectOne(new QueryWrapper<ContestItemUserEntity>().eq("id", order.getReservationId()));
                        if (itemUser != null) {
                            contestItem = contestItemMapper.selectOne(new QueryWrapper<ContestItemEntity>().eq("id", itemUser.getContestItemId()));
                        }
                    }
                    var game = authenticatedGameDao.selectById(contestItem != null ? contestItem.getMainId() : null);
                    var template = templateMapper.selectOne(new QueryWrapper<TemplateEntity>().eq("id", messageEntity.getTemplateId()));
                    if (template != null && contestItem != null && game != null) {
                        messageEntity.setContent(
                                templateReplace(template.getContent(), game, contestItem)
                        );
                    }
                }
            } else if (messageEntity.getBindingType().equals(MessageBindingType.MANAGE_GAME.getCode())) {
                AuthenticatedGameAuditLogMapper authenticatedGameAuditLogMapper =
                        SpringContextUtils.getBean(AuthenticatedGameAuditLogMapper.class);
                AuthenticatedGameDraftMapper authenticatedGameDraftMapper =
                        SpringContextUtils.getBean(AuthenticatedGameDraftMapper.class);
                TemplateMapper templateMapper = SpringContextUtils.getBean(TemplateMapper.class);
                var template = templateMapper.selectOne(new QueryWrapper<TemplateEntity>().eq("id", messageEntity.getTemplateId()));
                if (template != null) {
                    messageEntity.setContent(
                            templateReplace(
                                    template.getContent(),
                                    authenticatedGameDraftMapper,
                                    authenticatedGameAuditLogMapper,
                                    messageEntity.getBindingId()
                            )
                    );
                }
            } else if (messageEntity.getBindingType().equals(MessageBindingType.REGISTRATION.getCode())) {
                // 这里的bindingId是contestItemUserId
                ContestItemUserMapper contestItemUserMapper = SpringContextUtils.getBean(ContestItemUserMapper.class);
                var contestItemUser = contestItemUserMapper.selectOne(new QueryWrapper<ContestItemUserEntity>().eq("id", messageEntity.getBindingId()));
                TemplateMapper templateMapper = SpringContextUtils.getBean(TemplateMapper.class);
                var template = templateMapper.selectOne(new QueryWrapper<TemplateEntity>().eq("id", messageEntity.getTemplateId()));
                if (template != null && contestItemUser != null) {
                    messageEntity.setContent(
                            templateReplace(template.getContent(), contestItemUser)
                    );
                }
            }
        }
        return messageEntity;
    }

    public String getPostOrderGoodsNameFormat(OrdersEntity order,
                                              OrderGoodMapper orderGoodMapper,
                                              GoodMapper goodMapper) {
        List<Integer> orderGoodsIdList = order.getPostOrderGoodsId()
                .lines()
                .flatMap(s -> List.of(s.split(",")).stream())
                .map(Integer::parseInt)
                .toList();

        List<OrderGoodsEntity> orderGoodsEntityList = orderGoodMapper.selectList(new QueryWrapper<OrderGoodsEntity>().in("id", orderGoodsIdList));

        return orderGoodsEntityList.stream()
                .map(orderGoods ->
                        goodMapper.selectOne(new QueryWrapper<GoodsEntity>().eq("id", orderGoods.getGoodsId())).getGoodsName()

                )
                .collect(Collectors.joining("、", "【", "】"));
    }
}

